﻿using System;
using System.Collections.Generic;
using System.Workflow;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Text;
using NUnit.Framework;
using WorkflowLibrary1;

namespace TestProject
{
    [TestFixture]
    public class WorkflowTests
    {
        WorkflowRuntime _runtime;
        ManualWorkflowSchedulerService _scheduler;
        Dictionary<string, object> _outputs;
        Exception _exception;

        [TestFixtureSetUp]
        public void StartWorkflow()
        {
            _runtime = new WorkflowRuntime();
            // Use a manual service to make the test synchronous
            _scheduler = new ManualWorkflowSchedulerService();
            _runtime.AddService(_scheduler);

            _runtime.WorkflowCompleted += new EventHandler<WorkflowCompletedEventArgs>(_runtime_WorkflowCompleted);
            _runtime.WorkflowTerminated += new EventHandler<WorkflowTerminatedEventArgs>(_runtime_WorkflowTerminated);
        }

        [SetUp]
        public void SetupTest()
        {
            _exception = null;
            _outputs = null;
        }

        void _runtime_WorkflowTerminated(object sender, WorkflowTerminatedEventArgs e)
        {
            _exception = e.Exception;
        }

        void _runtime_WorkflowCompleted(object sender, WorkflowCompletedEventArgs e)
        {
            _outputs = e.OutputParameters;
        }

        [TestFixtureTearDown]
        public void StopWorkflow()
        {
            _runtime.StopRuntime();
            _runtime.Dispose();
        }

        [Test]
        public void TestWorkflowAddNum()
        {
            Dictionary<string, object> parameters = new Dictionary<string,object>();
            parameters.Add("Number", 1);
            WorkflowInstance instance = _runtime.CreateWorkflow(typeof(Workflow1), parameters);
            instance.Start();
            _scheduler.RunWorkflow(instance.InstanceId);

            Assert.IsNull(_exception, "Workflow threw an exception");
            Assert.AreEqual(_outputs.Count, 2);

            int actual = (int)_outputs["Number"];

            Assert.AreEqual(2, actual);

        }
    }
}
